package com.jike.noobmoney.mvp.view.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.CountDownTimer;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jike.noobmoney.BuildConfig;
import com.jike.noobmoney.MyApplication;
import com.jike.noobmoney.R;
import com.jike.noobmoney.contants.ConstantValue;
import com.jike.noobmoney.entity.BaseEntity;
import com.jike.noobmoney.entity.TaskDetailEntity;
import com.jike.noobmoney.entity.VersionEntity;
import com.jike.noobmoney.mvp.view.fragment.UpdateFragment;
import com.jike.noobmoney.mvp.view.widget.PermissionDialog;
import com.jike.noobmoney.mvp.view.widget.PermissionTwoDialog;
import com.jike.noobmoney.net.RetrofitHelper;
import com.jike.noobmoney.util.ActivityManager;
import com.jike.noobmoney.util.AppInfoUtils;
import com.jike.noobmoney.util.Constant;
import com.jike.noobmoney.util.PermissionUtils;
import com.jike.noobmoney.util.SPUtils;
import com.jike.noobmoney.util.ToastUtils;
import com.pgyersdk.javabean.AppBean;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.umeng.commonsdk.UMConfigure;

import java.lang.reflect.Field;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LaunchActivity extends BaseActivity implements UpdateFragment.OnFragmentInteractionListener{

    @BindView(R.id.version)
    TextView version;
    @BindView(R.id.ll_show)
    LinearLayout ll_show;
    @BindView(R.id.checkBox)
    CheckBox checkBox;
    public Call<VersionEntity> taskDetail;

    @Override
    protected int layoutResID() {
        return R.layout.activity_launch;
    }

    @Override
    public boolean ismain() {
        return false;
    }

    @Override
    public Boolean isfits() {
        return false;
    }

    @Override
    protected void initData() {
        //版本信息
        try {
            PackageManager pm = getPackageManager();
            PackageInfo pi = pm.getPackageInfo(getPackageName(), PackageManager.GET_ACTIVITIES);

            if (pi != null) {
                String versionName = pi.versionName == null ? "v1.0.0" : pi.versionName;
                version.setText("小白赚钱 v" + versionName);
            }



        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        //友盟的日志
        UMConfigure.setLogEnabled(BuildConfig.DEBUG);

        String first = SPUtils.getInstance().getString(ConstantValue.SpType.first, "2");
        if (!"1".equals(first)) {
            PermissionDialog instance = PermissionDialog.getInstance();
            instance.show(getSupportFragmentManager(), "permission");
            instance.setClickCallback(() -> {
                //确认
                instance.dismiss();
                showPermission();
            });
        } else {
            showPermission();
        }
        String isselect = SPUtils.getInstance().getString(ConstantValue.SpType.isselect,"0");
        if(isselect.equals("0"))
        {
            ll_show.setVisibility(View.VISIBLE);
        }else
        {
            ll_show.setVisibility(View.GONE);
        }
    }

    private void showPermission() {
        new RxPermissions(this)
                .request(
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.CAMERA
                )
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        String imie = AppInfoUtils.getPhoneIMIE(this);
                        SPUtils.getInstance().put(ConstantValue.SpType.imie, imie);
                        SPUtils.getInstance().put(ConstantValue.SpType.first, "1");
                        //update();
                        getData(Constant.VERSIONCODE);
                    } else {
                        SPUtils.getInstance().put(ConstantValue.SpType.first, "2");
                        //用户拒绝了权限
                        PermissionTwoDialog permissionTwo = PermissionTwoDialog.getInstance();
                        permissionTwo.show(getSupportFragmentManager(), "permissiontwo");
                        permissionTwo.setClickCallback(() -> {
                            //去开启
                            permissionTwo.dismiss();
                            PermissionUtils permissionPageUtils = new PermissionUtils(LaunchActivity.this, 200);
                            permissionPageUtils.jumpPermissionPage();
                        });

                    }
                });
    }


    /**
     * 获取数据
     */
    private void getData(String version) {
        taskDetail = RetrofitHelper.getInstance().getVersionDetail(version);
        taskDetail.enqueue(new Callback<VersionEntity>() {
            @Override
            public void onResponse(Call<VersionEntity> call, Response<VersionEntity> response) {
                if (response != null) {
                    VersionEntity body = response.body();
                    if (body != null) {
                        if ("100".equals(body.getCode())) {
                            DialogFragmentFromBottom(body.getUrl(),body.getMsg());
                        } else {
                            startApp();
                        }
                    }

                }
            }

            @Override
            public void onFailure(Call<VersionEntity> call, Throwable t) {
                ToastUtils.showShortToastSafe(t.getMessage());
            }
        });


    }

    private void update() {
        PgyUpdateManager.register(LaunchActivity.this,
                new UpdateManagerListener() {
                    @Override
                    public void onUpdateAvailable(final String result) {
                        // 将新版本信息封装到AppBean中
                        final AppBean appBean = getAppBeanFromString(result);
                        AlertDialog alertDialog = new AlertDialog.Builder(LaunchActivity.this)
                                .setTitle("发现新版本,是否更新")
                                .setMessage("新版本:v" + appBean.getVersionName() + "\n" + appBean.getReleaseNote())
                                .setNegativeButton(
                                        "取消",
                                        (dialogInterface, i) -> {
                                            //startApp()
                                            ActivityManager.getAppManager().AppExit(LaunchActivity.this);
                                        }
                                )
                                .setPositiveButton(
                                        "好的",
                                        (dialog, which) ->
                                                startDownloadTask(LaunchActivity.this, appBean.getDownloadURL())
                                )
                                .show();


                        //必须在调用show方法后才可修改样式
                        try {
                            Field mAlert = AlertDialog.class.getDeclaredField("mAlert");
                            mAlert.setAccessible(true);
                            Object mController = mAlert.get(alertDialog);
                            Field mMessage = mController.getClass().getDeclaredField("mMessageView");
                            mMessage.setAccessible(true);
                            TextView mMessageView = (TextView) mMessage.get(mController);
                            mMessageView.setTextColor(Color.parseColor("#ADADAD"));     //message样式修改成红色

                            Field mTitle = mController.getClass().getDeclaredField("mTitle");
                            mMessage.setAccessible(true);
                            TextView mTitleView = (TextView) mTitle.get(mController);
                            mTitleView.setTextColor(Color.parseColor("#01BBD4")); //title样式修改成``色
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (NoSuchFieldException e) {
                            e.printStackTrace();
                        }
                        //直接获取按钮并设置
                        final Button pButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);//确认按键
                        pButton.setTextColor(Color.parseColor("#01BBD4"));

                        Button nButton = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);//取消
                        nButton.setTextColor(Color.parseColor("#AAAAAA"));


                    }

                    @Override
                    public void onNoUpdateAvailable() {
                        startApp();
                    }
                });

    }

    private void DialogFragmentFromBottom(String url,String msg) {
        showUpdateDialog(url,msg);
    }
    void showUpdateDialog(String url,String msg) {

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
        if (prev != null) {
            ft.remove(prev);
        }
        ft.addToBackStack(null);

        // Create and show the dialog.
        UpdateFragment newFragment = UpdateFragment.newInstance(url,msg);
        newFragment.show(ft, "dialog");
    }


    /**
     * 请求权限之后进入app
     */
    private void startApp() {
        new CountDownTimer(1000, 1000) {
            @Override
            public void onTick(long l) {

            }

            @Override
            public void onFinish() {

                String isselect = SPUtils.getInstance().getString(ConstantValue.SpType.isselect,"0");

                if(isselect.equals("0")){

                }else if(isselect.equals("1")) {
                    String userid = SPUtils.getInstance().getString(ConstantValue.SpType.userid);
                    if (!TextUtils.isEmpty(userid)) {
                        Intent intent = new Intent(LaunchActivity.this, MainActivity.class);
                        intent.putExtra("type", "hongbao");
                        startActivity(intent);
                        finish();
                    } else {
                        startActivity(new Intent(LaunchActivity.this, LoginActivity.class));
                        finish();
                    }
                }
            }
        }.start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (200 == requestCode) {
            showPermission();
        }
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    @Override
    public void onOk(String url) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);

    }

    @Override
    public void onCancle() {
        MyApplication.getInstance().setFlag(1);
        startApp();
    }

    @OnClick({R.id.go_to,R.id.tv_ys,R.id.tv_xy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_xy:
                //用户协议
                startActivity(new Intent(context, UserXYActivity.class));
                break;
            case R.id.tv_ys:
                //隐私协议
                startActivity(new Intent(context, YSActivity.class));
                break;
            case R.id.go_to:
                if(checkBox.isChecked())
                {
                    SPUtils.getInstance().put(ConstantValue.SpType.isselect,"1");
                    String userid = SPUtils.getInstance().getString(ConstantValue.SpType.userid);
                    if (!TextUtils.isEmpty(userid)) {
                        Intent intent = new Intent(LaunchActivity.this, MainActivity.class);
                        intent.putExtra("type", "hongbao");
                        startActivity(intent);
                        finish();
                    } else {
                        startActivity(new Intent(LaunchActivity.this, LoginActivity.class));
                        finish();
                    }
                }else
                {
                    Toast.makeText(context,"请勾选用户协议及隐私政策",Toast.LENGTH_SHORT).show();
                    return;
                }
                break;
        }
    }
}
